package com.xdxc.config;

import com.xdxc.emuns.ThreadPoolType;
import jakarta.annotation.PostConstruct;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.Arrays;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

@Configuration
public class ThreadPoolRegistry {
    private static final Map<ThreadPoolType, ThreadPoolTaskExecutor> registry = new ConcurrentHashMap<>();

    @PostConstruct
    public void init() {
        Arrays.stream(ThreadPoolType.values()).forEach(type -> {
            ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
            executor.setCorePoolSize(type.corePoolSize);
            executor.setMaxPoolSize(type.maxPoolSize);
            executor.setQueueCapacity(type.queueCapacity);
            executor.setThreadNamePrefix(type.name() + "-");
            executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
            executor.initialize();
            registry.put(type, executor);
        });
    }

    public static Executor getExecutor(ThreadPoolType type) {
        return registry.get(type);
    }
}